package com.jams.goodox.activity.serve.headhunter;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.hangzhou.jin.customview.TextMoreLayout;
import com.jams.goodox.BaseActivity;
import com.jams.goodox.R;
import com.jams.goodox.activity.common.ChooseListActivity;
import com.jams.goodox.activity.common.EditTextActivity;
import com.jams.goodox.entity.ChooseItem;
import com.jams.goodox.entity.JobBean;
import com.jams.goodox.entity.User;
import com.jams.goodox.entity.resp.AddTreatmentNameResp;
import com.jams.goodox.entity.resp.JobDetailResp;
import com.jams.goodox.entity.resp.WelfareTagsResp;
import com.jams.goodox.listen.DialogActionListener;
import com.jams.goodox.net.BaseEntity;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.services.HeadHunterService;
import com.jams.goodox.utils.CollectionUtils;
import com.jams.goodox.utils.DataCacheManager;
import com.jams.goodox.utils.ProgressDialogUtils;
import com.jams.goodox.utils.StringUtils;
import com.jams.goodox.utils.StyleUtil;
import com.jams.goodox.utils.ToastUtil;
import com.jams.goodox.utils.Utils;
import com.jams.goodox.utils.ViewUtils;
import com.jams.goodox.widget.PromptBuilderDialog;
import com.jams.library.commonAdapter.RecycleCommonAdapter;
import com.jams.library.commonAdapter.RecycleCommonViewHolder;
import com.jams.library.listener.OnRecycleItemClickListener;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import retrofit2.Call;

/**
 * create by 顾佳佳 on 2017/05/17
 * <p>
 * 添加职位信息
 */
public class AddJobInfoActivity extends BaseActivity {

    @Bind(R.id.tv_job_name)
    TextView tvJobName;
    @Bind(R.id.et_job_name)
    EditText etJobName;
    @Bind(R.id.tl_need_year)
    TextMoreLayout tlNeedYear;
    @Bind(R.id.tl_need_education)
    TextMoreLayout tlNeedEducation;
    @Bind(R.id.tl_job_desc)
    TextMoreLayout tlJobDesc;
    @Bind(R.id.et_job_mark)
    EditText etJobMark;
    @Bind(R.id.et_job_money)
    EditText etJobMoney;
    @Bind(R.id.rcv_welfare_tag)
    RecyclerView rcvWelfareTag;
    @Bind(R.id.tl_need_prise)
    TextMoreLayout tlNeedPrise;
    @Bind(R.id.rl_job_all)
    RelativeLayout rlJobAll;

    // 输入标签页面
    private View dialog;
    public static final int YearRequest = 102;
    public static final int EducationRequest = 103;
    public static final int JobRequest = 104;
    public static final int PriseRequest = 105;
    public static final String PositionId = "PositionId";

    private int yearNeed = -1;//年限选择position
    private int educationNeed = -1;//教育选择position
    private int priseNeed = -1;//薪酬选择
    private List<ChooseItem> tags;//福利标签
    private RecycleCommonAdapter<ChooseItem> recycleCommonAdapter;
    private String content;

    private List<ChooseItem> yearList, educationList, priseList;
    private String positionId;//职位id
    private JobBean jobBean;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_add_job_info;
    }

    @Override
    protected void init() {
        StyleUtil.titleBackKey(this, "添加职位信息");
        tvJobName.setFocusable(true);
        tvJobName.setFocusableInTouchMode(true);
        tvJobName.requestFocus();
        tags = new ArrayList<>();
        positionId = getIntent().getStringExtra(PositionId);
        yearList = CollectionUtils.arrayToList(getResources().getStringArray(R.array.year_need), yearNeed);
        educationList = CollectionUtils.arrayToList(getResources().getStringArray(R.array.education_need), educationNeed);
        priseList = CollectionUtils.arrayToList(getResources().getStringArray(R.array.prise_need), priseNeed);
        rcvWelfareTag.setLayoutManager(new GridLayoutManager(this, 4));
        rcvWelfareTag.setHasFixedSize(true);
        recycleCommonAdapter = new RecycleCommonAdapter<ChooseItem>(this, tags, R.layout.only_textview) {
            @Override
            public void convert(RecycleCommonViewHolder helper, ChooseItem item, int position) {
                setTagData(helper, item, position);
            }
        };
        rcvWelfareTag.setAdapter(recycleCommonAdapter);
        getTags(!TextUtils.isEmpty(positionId));
    }

    @OnClick({R.id.tl_need_year, R.id.tl_need_education, R.id.tl_job_desc, R.id.tl_need_prise, R.id.tv_save, R.id.tv_save_publish})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.tl_need_year:
                intent = new Intent(this, ChooseListActivity.class);
                intent.putExtra(ChooseListActivity.TITLE, "年限要求");
                intent.putExtra(ChooseListActivity.CHOOSE, (Serializable) CollectionUtils.arrayToList(getResources().getStringArray(R.array.year_need), yearNeed));
                startActivityForResult(intent, YearRequest);
                break;
            case R.id.tl_need_education:
                intent = new Intent(this, ChooseListActivity.class);
                intent.putExtra(ChooseListActivity.TITLE, "学历要求");
                intent.putExtra(ChooseListActivity.CHOOSE, (Serializable) CollectionUtils.arrayToList(getResources().getStringArray(R.array.education_need), educationNeed));
                startActivityForResult(intent, EducationRequest);
                break;
            case R.id.tl_job_desc:
                intent = new Intent(this, EditTextActivity.class);
                intent.putExtra(EditTextActivity.ETITLE, "职位描述");
                intent.putExtra(EditTextActivity.ERIGHT, getString(R.string.confirm));
                intent.putExtra(EditTextActivity.ECONTENT, content);
                intent.putExtra(EditTextActivity.EHINT, "请输入职位描述...");
                startActivityForResult(intent, JobRequest);
                break;
            case R.id.tl_need_prise:
                intent = new Intent(this, ChooseListActivity.class);
                intent.putExtra(ChooseListActivity.TITLE, "薪酬范围");
                intent.putExtra(ChooseListActivity.CHOOSE, (Serializable) CollectionUtils.arrayToList(getResources().getStringArray(R.array.prise_need), priseNeed));
                startActivityForResult(intent, PriseRequest);
                break;
            case R.id.tv_save:
                if (checkInputValid()) {
                    save(0);
                }
                break;
            case R.id.tv_save_publish:
                if (checkInputValid()) {
                    save(1);
                }
                break;
        }
    }

    //获取福利标签
    private void getTags(final boolean bool) {
        ProgressDialogUtils.show(this);
        enqueue(createCallService(HeadHunterService.class).getWelfareTags(DataCacheManager.getInstance().getUser().getEnterpriseId()), new RetrofitCallbackListener<WelfareTagsResp>() {
            @Override
            public void onSuccess(Call<WelfareTagsResp> call, WelfareTagsResp result) {
                tags.clear();
                if (CollectionUtils.hasData(result.getData())) {
                    tags.addAll(result.getData());
                }
                if (bool) {
                    getJobDetail();
                } else {
                    rlJobAll.setVisibility(View.VISIBLE);
                    ProgressDialogUtils.dismiss();
                }
                ChooseItem chooseItem = new ChooseItem();
                chooseItem.setIds(-1);
                chooseItem.setName("");
                chooseItem.setId("");
                tags.add(chooseItem);
                recycleCommonAdapter.notifyDataSetChanged();
            }

            @Override
            public void onError(String msg) {
                ProgressDialogUtils.dismiss();
            }
        });
    }

    //设置标签数据
    private void setTagData(RecycleCommonViewHolder helper, final ChooseItem item, int position) {
        if (item.getIds() == -1) {//添加标签的按钮
            helper.getView(R.id.tv_item).setBackgroundResource(R.mipmap.add_tag);
            helper.setText(R.id.tv_item, "");
        } else {
            helper.getView(R.id.tv_item).setBackgroundResource(item.isSelected() ? R.drawable.main_theme_radius : R.drawable.gray_stroke_bg);
            ((TextView) helper.getView(R.id.tv_item)).setTextColor(item.isSelected() ? ContextCompat.getColor(mContext, R.color.font_main) : ContextCompat.getColor(mContext, R.color.font_hint));
            helper.setText(R.id.tv_item, item.getName());
        }
        helper.setOnItemClickListener(new OnRecycleItemClickListener() {
            @Override
            public void itemClick() {
                if (item.getIds() == -1) {
                    showPopWindow();
                    return;
                }
                if (item.isSelected()) {
                    item.setSelected(false);
                    recycleCommonAdapter.notifyDataSetChanged();
                    return;
                }
                if (getSelectCount() > 3) {
                    ToastUtil.show(mContext, "只能选择4个标签");
                    return;
                }
                item.setSelected(!item.isSelected());
                recycleCommonAdapter.notifyDataSetChanged();
            }
        });
        helper.setOnLongItemClickListener(new OnRecycleItemClickListener() {
            @Override
            public void itemClick() {
                if (item.getIds() == -1) {
                    return;
                }
                new PromptBuilderDialog(mContext)
                        .setContent("确定要删除该福利标签吗？")
                        .setNegative(R.string.cancel)
                        .setPositive(R.string.confirm)
                        .setActionClickListener(new DialogActionListener() {
                            @Override
                            public void confirm(DialogInterface dialog, int which) {
                                enqueue(createCallService(HeadHunterService.class).delWelfareTag(item.getId()), new RetrofitCallbackListener<BaseEntity>() {
                                    @Override
                                    public void onSuccess(Call<BaseEntity> call, BaseEntity result) {
                                        tags.remove(item);
                                        recycleCommonAdapter.notifyDataSetChanged();
                                    }

                                    @Override
                                    public void onError(String msg) {

                                    }
                                });
                            }

                            @Override
                            public void cancel(DialogInterface dialog, int which) {

                            }
                        }).show();
            }
        });
    }

    //添加标签
    private void addJobTag(final String tag) {
        if (tagIsExist(tag)) {
            ToastUtil.show(this, "该标签已存在！");
            return;
        }
        enqueue(createCallService(HeadHunterService.class).addWelfareTag(DataCacheManager.getInstance().getUser().getEnterpriseId(), tag), new RetrofitCallbackListener<AddTreatmentNameResp>() {
            @Override
            public void onSuccess(Call<AddTreatmentNameResp> call, AddTreatmentNameResp result) {
                if(result.getData() != null){
                    tags.add(tags.size() - 1, result.getData());
                    recycleCommonAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onError(String msg) {

            }
        });
    }

    //获取选中的数量
    private int getSelectCount() {
        int count = 0;
        for (int i = 0; i < tags.size(); i++) {
            if (tags.get(i).isSelected()) {
                count++;
            }
        }
        return count;
    }

    //判断该标签是否存在
    private boolean tagIsExist(String tag) {
        for (int i = 0; i < tags.size(); i++) {
            if (tags.get(i).getName().equals(tag)) {
                return true;
            }
        }
        return false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 100) {
            switch (requestCode) {
                case YearRequest:
                    if (data != null) {
                        ChooseItem chooseItem = (ChooseItem) data.getSerializableExtra(ChooseListActivity.CHOOSE);
                        tlNeedYear.setRightText(chooseItem.getName());
                        yearNeed = chooseItem.getIds();
                    }
                    break;
                case EducationRequest:
                    if (data != null) {
                        ChooseItem chooseItem = (ChooseItem) data.getSerializableExtra(ChooseListActivity.CHOOSE);
                        tlNeedEducation.setRightText(chooseItem.getName());
                        educationNeed = chooseItem.getIds();
                    }
                    break;
                case JobRequest:
                    if (data != null) {
                        content = data.getStringExtra(EditTextActivity.ECONTENT);
                        if (!TextUtils.isEmpty(content)) {
                            if (content.length() > 12) {
                                tlJobDesc.setRightText(content.substring(0, 11) + "...");
                            } else {
                                tlJobDesc.setRightText(content);
                            }
                        }
                    }
                    break;
                case PriseRequest:
                    if (data != null) {
                        ChooseItem chooseItem = (ChooseItem) data.getSerializableExtra(ChooseListActivity.CHOOSE);
                        tlNeedPrise.setRightText(chooseItem.getName());
                        priseNeed = chooseItem.getIds();
                    }
            }
        }
    }

    //显示添加标签输入框
    private void showPopWindow() {
        dialog = findViewById(R.id.show_dialog);
        final EditText write_room_tag = (EditText) dialog.findViewById(R.id.write_room_tag);
        Utils.setFilter(write_room_tag);//非法字符过滤器
        TextView save_btn = (TextView) dialog.findViewById(R.id.save_btn);
        write_room_tag.requestFocus();
        openKeybord();
        dialog.setVisibility(View.VISIBLE);
        dialog.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (ViewUtils.isFastDoubleClick())
                    return;
                dialog.setVisibility(View.GONE);
                closeKeyboard();
            }
        });
        save_btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (ViewUtils.isFastDoubleClick())
                    return;
                downOk(write_room_tag);
            }
        });
        save_btn.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                 /*判断是否是“down”键*/
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    downOk(write_room_tag);
                    return true;
                }
                return false;
            }
        });
    }

    //隐藏添加标签输入框
    private void downOk(EditText write_room_tag) {
        String edit = write_room_tag.getText().toString().trim();
        if (!TextUtils.isEmpty(edit)) {
            addJobTag(edit);
        }
        dialog.setVisibility(View.GONE);
        closeKeyboard();
        write_room_tag.setText("");
    }

    private boolean checkInputValid() {
        if (TextUtils.isEmpty(etJobName.getText().toString())) {
            ToastUtil.show("请输入岗位名称");
            return false;
        }
        if (yearNeed == -1) {
            ToastUtil.show("请选择年限要求");
            return false;
        }
        if (educationNeed == -1) {
            ToastUtil.show("请选择学历要求");
            return false;
        }
        if (TextUtils.isEmpty(content)) {
            ToastUtil.show("请输入职位描述");
            return false;
        }
        if(priseNeed==-1){
            ToastUtil.show("请选择月薪范围");
            return false;
        }
        if (TextUtils.isEmpty(etJobMoney.getText().toString())) {
            ToastUtil.show("请输入猎头奖励");
            return false;
        }
        return true;
    }

    //获取职位详情
    private void getJobDetail() {
        enqueue(createCallService(HeadHunterService.class).getCompanyJobDetail(positionId), new RetrofitCallbackListener<JobDetailResp>() {
            @Override
            public void onSuccess(Call<JobDetailResp> call, JobDetailResp result) {
                ProgressDialogUtils.dismiss();
                jobBean = result.getData();
                if (jobBean != null) {
                    yearNeed = jobBean.getJobLifeRequire();
                    educationNeed = jobBean.getEducationRequire();
                    priseNeed = jobBean.getSalary();
                    content = jobBean.getJobDescrip();
                    etJobName.setText(jobBean.getJobName());
                    tlNeedYear.setRightText(yearList.get(yearNeed).getName());
                    tlNeedEducation.setRightText(educationList.get(educationNeed).getName());
                    if (content.length() > 12) {
                        tlJobDesc.setRightText(content.substring(0, 11) + "...");
                    } else {
                        tlJobDesc.setRightText(content);
                    }
                    tlNeedPrise.setRightText(priseList.get(priseNeed).getName());
                    etJobMark.setText(StringUtils.newString(jobBean.getRemark()));
                    etJobMoney.setText(StringUtils.doubleToIntegerString(jobBean.getReward()));
                    List<ChooseItem> tag = jobBean.getTreatment();
                    for (int i = 0; i < tag.size(); i++) {
                        for (int j = 0; j < tags.size(); j++) {
                            if (tags.get(j).getId().equals(tag.get(i).getId())) {
                                tags.get(j).setSelected(true);
                            }
                        }
                    }
                    recycleCommonAdapter.notifyDataSetChanged();
                }
                rlJobAll.setVisibility(View.VISIBLE);
            }

            @Override
            public void onError(String msg) {
                ProgressDialogUtils.dismiss();
            }
        });
    }

    //保存
    private void save(int status) {
        User user = DataCacheManager.getInstance().getUser();
        if (user == null) {
            return;
        }
        if (jobBean == null) {
            jobBean = new JobBean();
        }
        jobBean.setJobName(etJobName.getText().toString());
        jobBean.setEducationRequire(educationNeed);
        jobBean.setEnterpriseId(user.getEnterpriseId());
        jobBean.setJobDescrip(content);
        jobBean.setJobLifeRequire(yearNeed);
        jobBean.setRemark(etJobMark.getText().toString());
        jobBean.setReward(StringUtils.stringToDouble(etJobMoney.getText().toString()));
        jobBean.setSalary(priseNeed);
        jobBean.setStatus(status);
        List<ChooseItem> chooseItems = new ArrayList<>();
        for (ChooseItem chooseItem : tags) {
            if (chooseItem.isSelected()) {
                chooseItems.add(chooseItem);
            }
        }
        jobBean.setTreatment(chooseItems);

        String strJson = new Gson().toJson(jobBean);
        ProgressDialogUtils.show(this);
        enqueue(createCallService(HeadHunterService.class).saveCompanyJob(strJson), new RetrofitCallbackListener<BaseEntity>() {
            @Override
            public void onSuccess(Call<BaseEntity> call, BaseEntity result) {
                ProgressDialogUtils.dismiss();
                setResult(1992);
                finish();
            }

            @Override
            public void onError(String msg) {
                ProgressDialogUtils.dismiss();
            }
        });
    }
}
